package ottawa.testing.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class AbstractHibernateDAO 
	extends HibernateDaoSupport
	implements CoreHibernateDAO
{
	
	protected final Log log = LogFactory.getLog(getClass());
	
	public void salvarObjeto(Object entity) 
		throws HibernateException 
	{		
		try
		{
			getSession().setFlushMode(FlushMode.AUTO);
			getHibernateTemplate().save(entity);
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL GUARDAR", ex);
			throw ( ex );
		}	
	}
	
	public void actualizarObjeto(Object entity)
		throws HibernateException
	{
		try
		{
			getSession().setFlushMode(FlushMode.AUTO);
			getHibernateTemplate().update(entity);
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL ACTUALIZAR", ex);
			throw ( ex );
		}
	}
	
	public void salvarOActualizarObjeto(Object entity)
		throws HibernateException
	{
		try
		{
			getSession().setFlushMode(FlushMode.AUTO);
			getHibernateTemplate().saveOrUpdate(entity);
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL SALVAR O ACTUALIZAR", ex);
			throw ( ex );
		}
	}
	
	public void borrarObjeto(Object entity)
		throws HibernateException
	{
		try
		{
			getSession().setFlushMode(FlushMode.AUTO);
			getHibernateTemplate().delete(entity);
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL ELIMINAR", ex);
			throw ( ex );
		}
	}
	
	public List listarObjeto(Class clazz)
		throws HibernateException
	{
		try
		{
			return getHibernateTemplate().find("FROM " + clazz.getName());
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL LISTAR", ex);
			throw ( ex );
		}
	}

	public Object obtenerObjeto(Class clazz, Long id)
		throws HibernateException
	{
		try
		{
			return getHibernateTemplate().load(clazz, id);
		}
		catch ( HibernateException ex )
		{
			log.error("ERROR EN BASE DE DATOS AL OBTENER OBJETO", ex);
			throw ( ex );
		}
	}
	
}
